<template>
  <div class="food-intake-input">
    <!-- 食物选择区域 - 紧凑布局 -->
    <div class="food-selection-compact">
      <div class="selection-row">
        <div class="form-item food-select">
          <label class="form-label">选择食物</label>
          <n-select
            v-model:value="selectedFoodId"
            placeholder="请选择食物"
            :options="foodOptions"
            filterable
          />
        </div>
        <div class="form-item amount-input" v-if="selectedFood">
          <label class="form-label">摄入量 (克)</label>
          <n-input-number
            v-model:value="intakeAmount"
            placeholder="摄入量"
            :min="1"
            :max="2000"
            :step="1"
          />
        </div>
        <div class="add-button-container">
          <n-button
            type="primary"
            size="medium"
            @click="addFoodIntake"
            :disabled="!selectedFood || !intakeAmount"
            class="add-food-btn"
          >
            <template #icon>
              <n-icon>
                <Add />
              </n-icon>
            </template>
            添加食物
          </n-button>
        </div>
      </div>

      <!-- 历史选择食物标签 -->
      <div class="food-history" v-if="historyFoods.length > 0">
        <label class="form-label">今日历史选择</label>
        <div class="history-tags">
          <n-tag
            v-for="food in historyFoods"
            :key="food.id"
            :type="getTagColor(food.id)"
            :bordered="false"
            size="small"
            class="history-tag"
            @click="selectHistoryFood(food)"
            style="cursor: pointer;"
          >
            {{ food.name_zh }}
          </n-tag>
        </div>
      </div>
    </div>
    <!-- 已添加的食物列表 -->
    <div class="food-intake-list" v-if="modelValue.length > 0">
      <h4>已添加的食物</h4>
      <div class="intake-items">
        <div v-for="(intake, index) in modelValue" :key="index" class="intake-item">
          <div class="intake-info">
            <h5>{{ intake.food.name_zh }}</h5>
            <p>{{ intake.amount_g }}g</p>
          </div>
          <div class="intake-nutrition">
            <span class="energy">{{ Math.round(intake.calculated_nutrition?.energy_kcal || 0) }} 千卡</span>
            <span class="protein">蛋白质 {{ (intake.calculated_nutrition?.protein_g || 0).toFixed(1) }}g</span>
          </div>
          <n-button
            quaternary
            type="error"
            size="small"
            @click="removeFoodIntake(index)"
          >
            删除
          </n-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { Add } from '@vicons/ionicons5';
import type { Food, FoodIntake } from '@/types';
import { calculateNutrition, validateFoodIntakeAmount } from '@/utils/nutrition';

interface Props {
  foods: Food[];
  modelValue: FoodIntake[];
}

interface Emits {
  (e: 'update:modelValue', value: FoodIntake[]): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const selectedFoodId = ref<number | null>(null);
const intakeAmount = ref<number>(100); // 默认100g
const historyFoodIds = ref<number[]>([]); // 历史选择的食物ID列表

// LocalStorage 键名
const HISTORY_STORAGE_KEY = 'food_selection_history';
const HISTORY_DATE_KEY = 'food_selection_history_date';

// 计算属性
const foodOptions = computed(() => {
  return props.foods.map((food) => ({
    label: food.name_zh || '',
    value: food.id,
    food,
  }));
});

const selectedFood = computed(() => {
  if (!selectedFoodId.value) return null;
  return props.foods.find((food) => food.id === selectedFoodId.value) || null;
});

// 历史食物列表（去重并限制数量）
const historyFoods = computed(() => {
  const uniqueIds = [...new Set(historyFoodIds.value)];
  return uniqueIds
    .map(id => props.foods.find(food => food.id === id))
    .filter((food): food is Food => food !== undefined)
    .slice(0, 10); // 最多显示10个历史记录
});

// 获取今天的日期字符串
const getTodayDateString = (): string => {
  const today = new Date();
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
};

// 从 localStorage 加载历史记录
const loadHistory = () => {
  try {
    const savedDate = localStorage.getItem(HISTORY_DATE_KEY);
    const todayDate = getTodayDateString();

    // 如果日期不是今天，清除历史记录
    if (savedDate !== todayDate) {
      localStorage.removeItem(HISTORY_STORAGE_KEY);
      localStorage.setItem(HISTORY_DATE_KEY, todayDate);
      historyFoodIds.value = [];
      return;
    }

    // 加载历史记录
    const savedHistory = localStorage.getItem(HISTORY_STORAGE_KEY);
    if (savedHistory) {
      historyFoodIds.value = JSON.parse(savedHistory);
    }
  } catch (error) {
    console.error('加载历史记录失败:', error);
    historyFoodIds.value = [];
  }
};

// 保存历史记录到 localStorage
const saveHistory = () => {
  try {
    localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(historyFoodIds.value));
    localStorage.setItem(HISTORY_DATE_KEY, getTodayDateString());
  } catch (error) {
    console.error('保存历史记录失败:', error);
  }
};

// 添加食物到历史记录
const addToHistory = (foodId: number) => {
  // 如果已存在，先移除（这样可以把它移到最前面）
  const index = historyFoodIds.value.indexOf(foodId);
  if (index > -1) {
    historyFoodIds.value.splice(index, 1);
  }

  // 添加到开头
  historyFoodIds.value.unshift(foodId);

  // 保存到 localStorage
  saveHistory();
};

// 点击历史标签选择食物
const selectHistoryFood = (food: Food) => {
  selectedFoodId.value = food.id;
};

// 根据食物ID生成标签颜色（使用固定的颜色映射）
const tagColors = ['default', 'success', 'warning', 'error', 'info'] as const;
const getTagColor = (foodId: number): typeof tagColors[number] => {
  // 使用食物ID生成一个稳定的颜色索引
  return tagColors[foodId % tagColors.length];
};

// 添加食物摄入
const addFoodIntake = () => {
  if (!selectedFood.value || !intakeAmount.value) return;

  const validation = validateFoodIntakeAmount(intakeAmount.value);
  if (!validation.valid) {
    console.error(validation.message);
    // TODO: 显示错误提示
    return;
  }

  const intake: FoodIntake = {
    food_id: selectedFood.value.id,
    food: selectedFood.value,
    amount_g: intakeAmount.value,
    calculated_nutrition: calculateNutrition(selectedFood.value, intakeAmount.value),
  };

  emit('update:modelValue', [...props.modelValue, intake]);

  // 添加到历史记录
  addToHistory(selectedFood.value.id);

  // 重置选择
  selectedFoodId.value = null;
  intakeAmount.value = 100;
};

// 移除食物摄入
const removeFoodIntake = (index: number) => {
  const newIntakes = [...props.modelValue];
  newIntakes.splice(index, 1);
  emit('update:modelValue', newIntakes);
};

// 组件挂载时加载历史记录
onMounted(() => {
  loadHistory();
});
</script>

<style scoped>
.food-intake-input {
  padding: 0px;
  width: 100%;
}
.food-selection-compact {
  margin-bottom: 16px;
  width: 100%;
}
.selection-row {
  display: flex;
  gap: 8px;
  align-items: end;
  flex-wrap: wrap;
  width: 100%;
}
.food-select {
  flex: 2;
  min-width: 200px;
}
.amount-input {
  flex: 1;
  min-width: 120px;
}
.add-button-container {
  display: flex;
  align-items: end;
  padding-bottom: 2px;
}
.add-food-btn {
  white-space: nowrap;
  font-weight: 600;
}

/* 历史选择区域 */
.food-history {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  width: 100%;
}
.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 6px;
}
.history-tag {
  transition: all 0.2s ease;
}
.history-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .selection-row {
    flex-direction: column;
    align-items: stretch;
  }
  .food-select,
  .amount-input {
    flex: none;
    min-width: auto;
    width: 100%;
  }
  .add-button-container {
    align-items: stretch;
  }
  .add-food-btn {
    width: 100%;
  }
}
.form-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 0;
  width: 100%;
}
.form-label {
  font-size: 12px;
  font-weight: 500;
  color: #666;
  margin-bottom: 2px;
}
.intake-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
}
.food-intake-list {
  margin-bottom: 16px;
  margin-top: 16px;
  width: 100%;
}
.food-intake-list h4 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 13px;
  font-weight: 600;
}
.intake-item {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background: #fafafa;
}
.intake-info {
  flex: 1;
}
.intake-info h5 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
}
.intake-info p {
  margin: 0;
  color: var(--ion-color-medium);
  font-size: 14px;
}
.intake-nutrition {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-right: 12px;
}
.intake-nutrition span {
  font-size: 12px;
  margin: 2px 0;
}
.energy {
  color: var(--ion-color-danger);
  font-weight: 600;
}
.protein {
  color: var(--ion-color-success);
}
</style>